package com.example.demo9;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private EditText editText;  //文本框
    private Button btn_holdUp,btn_unblock;  //拦截按钮
    private OutcallReceiver outcallReceiver;    //定义OutcallReceiver对象
    private static final String OUT_CALL_PHONE="android.intent.action.NEW_OUTGOING_CALL";   //系统电话

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initMyReceiver();
    }
    //初始化控件
    private void initView() {
        editText=findViewById(R.id.ed_text);
        btn_holdUp=findViewById(R.id.btn_holdUp);
        btn_unblock=findViewById(R.id.btn_unblock);
        btn_holdUp.setOnClickListener(this);
        btn_unblock.setOnClickListener(this);

    }
    //设置按钮监听事件
    @Override
    public void onClick(View view) {
        //获取文本框中内容
        String data=editText.getText().toString().trim();
        SharedPreferences sp=getSharedPreferences("config",MODE_PRIVATE);
        SharedPreferences.Editor edit=sp.edit();
        //判断文本框是否有内容
        if (!TextUtils.isEmpty(data))
        {
            switch (view.getId())
            {
                case R.id.btn_holdUp:       //添加拦截
                    edit.putString("phone",data);
                    Toast.makeText(this, "添加拦截", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.btn_unblock:      //解除拦截
                    edit.remove("phone");
                    Toast.makeText(this, "删除拦截", Toast.LENGTH_SHORT).show();
                    break;
            }
            edit.commit();  //提交
        }
    }
    //初始化注册广播
    private void initMyReceiver() {
        outcallReceiver=new OutcallReceiver();  //实例化OutcallReceiver对象
        IntentFilter filter=new IntentFilter(); //定义IntentFilter
        filter.addAction(OUT_CALL_PHONE);
        //注册广播
        registerReceiver(outcallReceiver,filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(outcallReceiver);    //销毁
    }


}